package com.yc.demo.d0110;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;

/**
 * 1. 继承
 *      自定义Servlet
 *          => HttpServlet    专用于 http 协议的 servlet
 *              => GenericServlet     通用Servlet => 应用到所有协议：http,ftp...
 *                  => Servlet,ServletConfig (配置接口)
 * 2. 实现(覆盖)
 *      实现doXXX 方法：doGet 和 doPost 是最常用的
 *      doGet 只能处理 get 类型的请求
 *      doPost 只能处理 post 类型的请求
 * 3. 配置
 *      1）web.xml
 *      2）注解方式
 *          配置地址：1. /开头, 不以 / 会导致服务器启动失败
 *                  2. 地址全局唯一
 *          404：地址错误
 *          405：方法不正确
 *              post 请求 ==> form 提交 or AJXA 提交
 *              其他都是 get 请求
 */

@WebServlet(value="/week", loadOnStartup = 2,
        initParams = @WebInitParam(
                name = "myname",
                value = "李四"
        ))
public class weekServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("======== WeekServlet: service");

        Calendar calendar = Calendar.getInstance();
        final int week = calendar.get(Calendar.DAY_OF_WEEK);
        resp.getWriter().print("星期："+week);

    }

    @Override
    public void destroy() {
        System.out.println("=========== WeekServlet: destroy");
    }

    @Override
    public void init() throws ServletException {
        final ServletConfig servletConfig = this.getServletConfig();
        final String myname = servletConfig.getInitParameter("myname");
        System.out.println("=========== WeekServlet: init" + myname);

    }
}
